package com.flappySeeker.controller;


import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.flappySeeker.common.BaseDaoImp;
import com.flappySeeker.util.GetTools;
import com.flappySeeker.util.alipay.util.AlipayNotify;

@Controller
@RequestMapping("/alipay")
public class AlipayAction {
	
	@Autowired
	private BaseDaoImp baseDaoImp;
	
	public BaseDaoImp getBaseDaoImp() {
		return baseDaoImp;
	}
	public void setBaseDaoImp(BaseDaoImp baseDaoImp) {
		this.baseDaoImp = baseDaoImp;
	}
	
	/**
	 * 买家支付完成后的跳转页面
	 * @param ordernum, subject,body,totalfee
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/ReturnUrl")
	public String  ReturnUrl(HttpServletRequest request, Model model){
		int r = 0;//SQL执行的状态值
		
		try{
			/*response.setContentType("text/html");
			response.setCharacterEncoding("utf-8");*/
			Map<String,String> params = result(request);
			String trade_status = request.getParameter("trade_status");		//交易状态
			String order_num = request.getParameter("out_trade_no");		//交易订单号
			//PrintWriter out = response.getWriter();
//			if(AlipayNotify.verify(params)){//验证成功，正式发布时使用
			if(true){//验证成功-本地模拟测试用。
				if(trade_status.equals("TRADE_FINISHED")){ //失败页面
					return "test/order_error.jsp";
					//request.getRequestDispatcher("../jsp/test/order_error.jsp").forward(request, response);
				} else if (trade_status.equals("TRADE_SUCCESS")){//支付成功
	//				request.setAttribute("order", order);
					if(r<=0){
						r = baseDaoImp.update(
							"UPDATE tb_userinfo SET ispay='2'  WHERE ordernum = '"+order_num+"'"
						);
						Map<String,Object> list = baseDaoImp.sqlformap("select userid,username,usertel,verificode,vsmscode,resultsurl from tb_userinfo where " +
								"ordernum = '"+order_num+"'");
						request.getSession().setAttribute("sernum1", list.get("verificode"));
						return "test/order_success.jsp";
						//request.getRequestDispatcher("../jsp/test/order_success.jsp").forward(request, response); 
					}
				}
			}else{//验证失败
				return "test/order_error.jsp";
				//out.println("验证失败");
			}
		}catch (Exception e) {
			e.printStackTrace();
			return "/jsp/test/order_error.jsp";
		}
		return null;
	}
	
	/**
	 * 买家支付完成后的跳转页面，进行分润
	 * @param ordernum, subject,body,totalfee
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/NotifyUrl")
	public void NotifyUrl(HttpServletRequest request, HttpServletResponse response){
		try{
			response.setContentType("text/html");
			response.setCharacterEncoding("utf-8");
			Map<String,String> params = result(request);
			String trade_status = request.getParameter("trade_status");		//交易状态
			PrintWriter out = response.getWriter();
			if(AlipayNotify.verify(params)){//验证成功
				if(trade_status.equals("TRADE_FINISHED")){
					
				} else if (trade_status.equals("TRADE_SUCCESS")){
					//分润接口
				}
				out.println("success");
			}else{//验证失败
				out.println("fail");
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 处理结果，结果封装
	 */
	private Map<String,String> result(HttpServletRequest request){
		try {
			Map<String,String> params = new HashMap<String,String>();
			@SuppressWarnings("rawtypes")
			Map requestParams = request.getParameterMap();
			for (@SuppressWarnings("rawtypes")
			Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i]
							: valueStr + values[i] + ",";
				}
				//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
					valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");
				params.put(name, valueStr);
			}
			return params;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}
}
